package com.tlkj.common.curd.config;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

import static com.tlkj.common.curd.config.CommonCurdMyBatisConfig.COMMON_CURD_MAPPER_LOCATION;

/**
 * 加载Common CURD Mapper.
 * @author flyong86
 */
@Component
public class MyBatisMapperLoaderPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof SqlSessionFactory) {
            SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) bean;
            Configuration configuration = sqlSessionFactory.getConfiguration();
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            try {
                Resource[] resources = resolver.getResources(COMMON_CURD_MAPPER_LOCATION);
                for (Resource resource : resources) {
                    try (InputStream inputStream = resource.getInputStream()) {
                        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(inputStream, configuration, resource.toString(), configuration.getSqlFragments());
                        xmlMapperBuilder.parse();
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("Failed to load common curd mappers", e);
            }
        }
        return bean;
    }
}
